﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZFS.Library;
using ZFS.Model;
using ZFSData.InterFace.User;

namespace ZFSData.Manager
{
    public class MenuManager : BaseDal<tb_Menu>, IMenu
    {
        public bool ExistEntity(tb_Menu entity)
        {
            return base.ExistEntity(ExpressionHelper.GenerateQueryExp(entity));
        }

        public List<View_MenuTree> GetMenuTrees()
        {
            using (var db = new ZFSConfig())
            {
                var result = db.Database.SqlQuery<View_MenuTree>(
                    "SELECT a.isid, a.MenuName, a.MenuCaption, a.ParentName, b.AuthorityName, b.AuthorityValue, a.MenuCode" +
                    "  FROM " +
                    "dbo.tb_Menu AS a " +
                    "LEFT OUTER JOIN dbo.tb_AuthorityItem AS b ON b.AuthorityValue & " +
                    "a.MenuAuthorities = b.AuthorityValue").ToList();
                return result;
            }
        }

        public List<tb_Menu> GetModels(tb_Menu search)
        {
            return base.GetModels(ExpressionHelper.GenerateQueryExp(search));
        }

        public List<tb_Menu> GetPagingModels(int pageIndex, int pageSize, out int totalCount, tb_Menu search, bool Asc = false)
        {
            Expression<Func<tb_Menu, int>> orderexp = x => x.isid;

            return base.GetPagingModels(pageIndex, pageSize, out totalCount, ExpressionHelper.GenerateQueryExp(search), orderexp, Asc);
        }

        /// <summary>
        /// 新增更新模块信息
        /// </summary>
        /// <param name="tb_Menus"></param>
        /// <returns></returns>
        public bool UpdateMenus(List<tb_Menu> tb_Menus)
        {
            using (var db = new ZFSConfig())
            {
                tb_Menus.ForEach(q =>
                {
                    var row = db.tb_Menu.FirstOrDefault(x => x.MenuCode.Equals(q.MenuCode));
                    if (row != null)
                    {
                        row.MenuName = q.MenuName; ;
                        row.MenuNameSpace = q.MenuNameSpace;
                        row.MenuCaption = q.MenuCaption;
                        row.MenuAuthorities = q.MenuAuthorities;
                        DbEntityEntry dbEntity = db.Entry<tb_Menu>(row);
                        dbEntity.State = System.Data.Entity.EntityState.Modified;
                    }
                    else
                    {
                        db.Set<tb_Menu>().Add(q);
                    }
                });
                return db.SaveChanges() > 0 ? true : false;
            }
        }
    }
}
